package com.hubiwei.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.hubiwei.gmall.realtime.app.BaseAppV1;
import com.hubiwei.gmall.realtime.common.Constant;
import com.hubiwei.gmall.realtime.util.AtguiguUtil;
import com.hubiwei.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;


public class DwdLogApp extends BaseAppV1 {
    
    public static final String PAGE = "page";
    public static final String DISPLAY = "display";
    public static final String START = "start";
    
    public static void main(String[] args) {
        new DwdLogApp().init(2001, 1, "DwdLogApp", "DwdLogApp", Constant.TOPIC_ODS_LOG);
        
    }
    
    @Override
    public void run(StreamExecutionEnvironment env,
                    DataStreamSource<String> stream) {
        /*
          1. 区分新老客户  对已有的字段 is_new做一个纠正
          
          2. 分流: 启动日志  页面日志  曝光日志
          
          3. 把不同的流的数据写入到不同的topic中
        
         */
        //  1. 区分新老客户  对已有的字段 is_new做一个纠正
        SingleOutputStreamOperator<JSONObject> validateStream = distinguishNewOrOld(stream);
        // 2. 分流: 启动日志  页面日志  曝光日志
        HashMap<String, DataStream<JSONObject>> threeStreams = splitStream(validateStream);
        // 3. 把不同的流的数据写入到不同的topic中
        writeToKafka(threeStreams);
        
    }
    
    private void writeToKafka(HashMap<String, DataStream<JSONObject>> threeStreams) {
        
        threeStreams
            .get(START)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_START));
        
        threeStreams
            .get(DISPLAY)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_DISPLAY));
        
        threeStreams
            .get(PAGE)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_PAGE));
        
    }
    
    // 2. 分流: 启动日志  页面日志  曝光日志
    private HashMap<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> stream) {
        
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>(PAGE) {};
        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>(DISPLAY) {};
        
        SingleOutputStreamOperator<JSONObject> startStream = stream.process(new ProcessFunction<JSONObject, JSONObject>() {
            @Override
            public void processElement(JSONObject value,
                                       Context ctx,
                                       Collector<JSONObject> out) throws Exception {
                // 主流: 启动  测输出流2个: 页面和日志
                if (value.containsKey("start")) {
                    // 启动日志
                    out.collect(value);
                } else {
                    // 有可能是曝光或页面
                    if (value.containsKey("page")) {  // 页面
                        ctx.output(pageTag, value);
                    }
                    
                    if (value.containsKey("displays")) { // 曝光
                        JSONArray displays = value.getJSONArray("displays");
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject obj = displays.getJSONObject(i);
                            
                            obj.putAll(value.getJSONObject("common"));
                            obj.putAll(value.getJSONObject("page"));
                            
                            obj.put("ts", value.getLong("ts"));
                            ctx.output(displayTag, obj);
                        }
                    }
                    
                }
            }
        });
        
        DataStream<JSONObject> pageStream = startStream.getSideOutput(pageTag);
        DataStream<JSONObject> displayStream = startStream.getSideOutput(displayTag);
        
        HashMap<String, DataStream<JSONObject>> result = new HashMap<>();
        result.put(PAGE, pageStream);
        result.put(START, startStream);
        result.put(DISPLAY, displayStream);
        
        return result;
        
    }
    
    // 区别新老客户
    private SingleOutputStreamOperator<JSONObject> distinguishNewOrOld(DataStreamSource<String> stream) {
        /*
        使用事件时间+窗口, 找到第一条记录作为新用户, 其他都是老用户
         */
        return stream
            .map(JSON::parseObject)  // 方法引用
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
                
                private ValueState<Boolean> isFirstState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    isFirstState = getRuntimeContext().getState(new ValueStateDescriptor<Boolean>("isFirstState", Boolean.class));
                }
                
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    if (isFirstState.value() == null) {
                        // 这个设备id的第一个窗口, 找到时间戳最小的那个, 标记为新用户, 其他的标记为老用
                        
                        // 先更新状态
                        isFirstState.update(true);
                        
                        // 找时间最小的那个
                        List<JSONObject> list = AtguiguUtil.toList(elements);
                        //                        list.sort((o1, o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")));
                        list.sort(Comparator.comparing(o -> o.getLong("ts")));
                        
                        for (int i = 0; i < list.size(); i++) {
                            JSONObject obj = list.get(i);
                            if (i == 0) {
                                obj.getJSONObject("common").put("is_new", "1");
                            } else {
                                obj.getJSONObject("common").put("is_new", "0");
                            }
                            out.collect(obj);
                        }
                        
                    } else {
                        // 其他的窗口, 所有记录全部标记为老用户
                        for (JSONObject obj : elements) {
                            obj.getJSONObject("common").put("is_new", "0");
                            out.collect(obj);
                            
                        }
                    }
                    
                }
            });
        
    }
}
/*
侧输出流
 */